// lib/mongodb.ts
import { MongoClient, Db } from 'mongodb';

let client: MongoClient | null = null;
let db: Db | null = null;

// 获取数据库连接 URI
const uri = process.env.MONGODB_URI || ''; // 在 .env 文件中设置 MONGODB_URI
const dbName = process.env.MONGODB_DB;

export async function connectToDatabase() {
  if (client && db) {
    return { client, db };
  }

  if (!uri) {
    throw new Error('Please define the MONGODB_URI environment variable.');
  }

  client = await MongoClient.connect(uri);
  db = client.db(dbName);

  return { client, db };
}
